package com.may.ipersistence.config;

import com.may.ipersistence.pojo.Configuration;
import com.may.ipersistence.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @program: lagou
 * @description:
 * @author: Bobby.Ma
 * @create: 2020-10-31 16:06
 **/
public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream in) throws DocumentException {
        Document document = new SAXReader().read(in);
        Element root = document.getRootElement();
        String namespace = root.attributeValue("namespace");
        List<Element> selectNodes = root.selectNodes("//select");
        Map<String, MappedStatement> statementMap = selectNodes.stream().map(el -> {
            MappedStatement statement = new MappedStatement();
            statement.setId(el.attributeValue("id"));
            statement.setParamType(el.attributeValue("paramType"));
            statement.setResultType(el.attributeValue("resultType"));
            statement.setSql(el.getTextTrim());
            return statement;
        }).collect(Collectors.toMap(sta -> String.format("%s.%s",namespace,sta.getId()), sta -> sta));
        configuration.setStatementMap(statementMap);
    }
}
